import React, { Component } from 'react'
// import { SettingAlert } from '../../components'
import { TreeComponent, ModalForm } from '../../../components'
import Dimensions from 'react-dimensions'
import { fetchData  } from "../../../components/AjaxConsumer.js";
import { Button, Form, Row, Col, Modal, Spin, Alert } from 'antd';
const WrappedAdvancedSearchForm = Form.create()(ModalForm);
const confirm = Modal.confirm;
function warning() {
    Modal.warning({
        title: '请先选择一个节点',
    });
}

class TreeAndForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            selectKeys: [],
            selectedName: '',
            treeSelectBackData: '',
            optionData: []
        };
    }

    loading = (flag) => {
        this.setState({
            loading: flag
        })
    }
    //树组件点击，更新form
    upDataForm = (treeSelectBackData,selectedKeys,selectedName) => {
        //模拟延时，会有loading动画过度
        setTimeout(function(){
            this.setState({
                loading: false,
                treeSelectBackData: treeSelectBackData,
                selectedKeys: selectedKeys,
                selectedName: selectedName
            })
        }.bind(this),500)
        this.getOptionData();
    }
    //获取所属系统类型
    getOptionData = () =>{
        console.log("----------获取所属系统类型-----------");
        const options= {
            url: '/base/dic/get/cosmo_branch',
            type: 'get'
        };
        fetchData(this,options,this.getOptionDataCallBack);
    }
    //获取所属系统类型后回调
    getOptionDataCallBack = (resData)=>{
        console.log('---resData-------------', resData);
        this.setState({
            optionData: resData
        });
    }
    //增加节点
    addNode = () => {
        let selectedKeys = this.state.selectedKeys;
        let selectedName = this.state.selectedName;
        let belongSys = this.state.treeSelectBackData.data['dicCode'];
        if (typeof(selectedKeys) != 'undefined' && selectedKeys.length) {
            this.setState({
                treeSelectBackData: {reset:true,parentId:selectedKeys[0],parentName:selectedName,dicCode:belongSys}
            })
        } else {
            warning();
        }
        this.getOptionData();
    }
    //增加顶级节点
    addTopNode = () => {
        this.getOptionData();
        this.setState({
            treeSelectBackData: {addTop:true,parentId:'',parentName:'none'} //以后判断输出空表单使用
        })
    }
    //删除节点
    deleteNode = () => {
        let selectedKeys = this.state.selectedKeys;
        let selectedName = this.state.selectedName;
        if (typeof(selectedKeys) != 'undefined' && selectedKeys.length) {
            let options = {
                url: '/base/resource/d/',          //请求地址
                type: 'post',    //请求方式
                contentType: 'application/x-www-form-urlencoded',
                condition: {
                    resourceId: selectedKeys[0]
                    //   deleteId: checkedKeys
                }   //请求条件
            };
            let that = this;
            confirm({
                title: '提示',
                content: '确定要删除吗?',
                onOk() {
                    fetchData(that, options, that.callbackUpdata);
                },
                onCancel() {
                    console.log('Cancel');
                },
            });

        } else {
            warning();
        }
    }
    //出现初始页面（请选择左侧节点）
    callbackUpdata = (resData) => {
        this.setState({
            treeSelectBackData: null,
            selectedKeys: [],
            selectedName: null
        })
        //从新加载tree组件
        if (this.refs.TreeComponent.refleshData){
            this.refs.TreeComponent.refleshData();
        }
    }

    render() {
        //高度自适应
        let {containerHeight, subtractHeight, ...props} = this.props;
        //subtractHeight 和 subtractWidth 是页面传过来的值
        if(typeof subtractHeight !== 'undefined'){
            containerHeight = containerHeight - subtractHeight;
        }

        let optionData = this.state.optionData.data ? this.state.optionData.data : [];
        let newFormObj = this.state.treeSelectBackData ? this.state.treeSelectBackData : {code:'0'};
        let formAlerSize = 'large'; //弹出框的大小 只有'large'和'small'两种值 （必须,输错时默认为large）
        //正常渲染的表单
        let getFormData = [
            {
                type : 'input',
                showName : '父级资源名称',
                name : 'parentName',
                initialValue : newFormObj.data?newFormObj.data.parentName:'none',
                disable: true
            },{
                type : 'hiddenInput',
                name : 'resourceId',
                initialValue : newFormObj.data?newFormObj.data.resourceId:'',
            },{
                type : 'select',
                showName : '资源类型',
                name : 'resourceType',
                optionList:[
                    {
                        optionKey:'1',
                        optionShow:'菜单'
                    },{
                        optionKey:'2',
                        optionShow:'按钮'
                    },{
                        optionKey:'3',
                        optionShow:'手持'
                    }
                ],
                initialValue : newFormObj.data?newFormObj.data.resourceType:'',
                required:'required'
            },
            {
                type : 'input',
                showName : '资源名称',
                name : 'resourceName',
                initialValue : newFormObj.data?newFormObj.data.resourceName:'',
                required:'required'  //选填
            },
            {
                type : 'input',
                showName : 'URL',
                name : 'href',
                initialValue : newFormObj.data?newFormObj.data.href:''
            },
            {
                type : 'select',
                showName : '所属系统',
                name : 'dicCode',
                optionList:[
                    {
                        optionKey:'',
                        optionShow:''
                    }
                ],
                //initialValue : newFormObj.data?newFormObj.data.resourceType:'',
                required:'required'
            },
            {
                type : 'input',
                showName : '英文资源名称',
                name : 'engResourceName',
                initialValue : newFormObj.data?newFormObj.data.engResourceName:'',
                //required:'required'  //选填
            },
            {
                type : 'input',
                showName : '图标',
                name : 'iconClass',
                initialValue : newFormObj.data?newFormObj.data.iconClass:''
            },
            {
                type : 'number',     //必填 数字选择输入框
                showName : '排序',
                name : 'sortNo',
                initialValue : newFormObj.data?newFormObj.data.sortNo:''
            },
            {
                type : 'input',
                showName : '权限标识',
                name : 'permission',
                initialValue : newFormObj.data?newFormObj.data.permission:''
            },{
                type : 'textarea',
                showName : '备注',
                name : 'remark',
                initialValue : newFormObj.data?newFormObj.data.remark:''
            }
        ];
        if (optionData.length > 0){
            let options = [];
            optionData.map((item, index) => {
                let tempObj = {};
                tempObj.optionKey = item.dicCode;
                tempObj.optionShow = item.dicName;
                options.push(tempObj);
            })
            console.log(`options---------${options}`);
            getFormData[5].optionList = options;
            getFormData[5].initialValue = newFormObj.data?newFormObj.data.dicCode:'';
        }

        //增加节点的空表单
        let getResetFormData2 = [
            {

                type : 'input',
                showName : '父级资源名称',
                name : 'parentName',
                initialValue : newFormObj?newFormObj.parentName:'',
                required: true,
                disable: true
            },{
                type : 'hiddenInput',
                name : 'parentId',
                initialValue : newFormObj?newFormObj.parentId:'',
            },{
                type : 'select',
                showName : '资源类型',
                name : 'resourceType',
                optionList:[
                    {
                        optionKey:'1',
                        optionShow:'菜单'
                    },{
                        optionKey:'2',
                        optionShow:'按钮'
                    },{
                        optionKey:'3',
                        optionShow:'手持'
                    }
                ],
                initialValue : '1',
                required:'required'
            },
            {
                type : 'input',
                showName : '资源名称',
                name : 'resourceName',
                initialValue : '',
                required:'required'  //选填
            },
            {
                type : 'input',
                showName : 'URL',
                name : 'href',
                initialValue : ''
            },
            {
                type : 'select',
                showName : '所属系统',
                name : 'dicCode',
                optionList:[
                    {
                        optionKey:'',
                        optionShow:''
                    }
                ],
                //initialValue : newFormObj.data?newFormObj.data.dicCode:'',
                required:'required'
            },{
                type : 'input',
                showName : '英文资源名称',
                name : 'engResourceName',
                initialValue : '',
               // required:'required'  //选填
            },
            {
                type : 'input',
                showName : '图标',
                name : 'iconClass',
                initialValue : ''
            },
            {
                type : 'number',     //必填 数字选择输入框
                showName : '排序',
                name : 'sortNo',
                initialValue : '1'
            },
            {
                type : 'input',
                showName : '权限标识',
                name : 'permission',
                initialValue : ''
            },{
                type : 'textarea',
                showName : '备注',
                name : 'remark',
                initialValue : ''
            }
        ];
        if (optionData.length > 0) {
            let options = [];
            optionData.map((item, index) => {
                let tempObj = {};
                tempObj.optionKey = item.dicCode;
                tempObj.optionShow = item.dicName;
                options.push(tempObj);
            })
            getResetFormData2[5].optionList = options;
            getResetFormData2[5].initialValue = newFormObj?newFormObj.dicCode:'';
        }
        let ele;
        let loading = this.state.loading;
        if(loading) {
            ele =
                <div style={{
                    textAlign: 'center',
                    borderRadius: '4px',
                    height: '100%',
                    paddingTop:'20%'
                }}>
                    <Spin size="large" /> 加载中...
                </div>
        } else if (newFormObj.code == '1') {
            //正常渲染的表单
            ele =<div>
                <h2 style={{
                    textAlign: 'center',
                    color: '#666',
                    fontSize: '20px',
                    marginBottom: '20px'
                }}>
                    修改{this.state.selectedName}
                </h2>
                <WrappedAdvancedSearchForm
                    callbackUpdata={this.callbackUpdata}
                    formAlerSize={formAlerSize}
                    formUrl="/base/resource/u/"
                    getFormData={getFormData}
                />
            </div>

        } else if (newFormObj.reset) {

            //点击新增节点显示的空表单
            ele =<div>
                    <h2 style={{
                        textAlign: 'center',
                        color: '#666',
                        fontSize: '20px',
                        marginBottom: '20px'
                    }}>
                        添加子节点
                    </h2>
                    <WrappedAdvancedSearchForm
                        callbackUpdata={this.callbackUpdata}
                        formAlerSize={formAlerSize}
                        formUrl="/base/resource/c/"
                        getFormData={getResetFormData2}
                    />
                </div>
        } else if (newFormObj.addTop) {

            //点击新增顶级节点的空表单
            ele =<div>
                    <h2 style={{
                        textAlign: 'center',
                        color: '#666',
                        fontSize: '20px',
                        marginBottom: '20px'
                    }}>
                        添加主菜单
                    </h2>
                    <WrappedAdvancedSearchForm
                        callbackUpdata={this.callbackUpdata}
                        formAlerSize={formAlerSize}
                        formUrl="/base/resource/c/"
                        getFormData={getResetFormData2}
                    />
                </div>
        } else {
            //未点击页面
            ele =
                <Alert
                    style={{marginRight:'50px'}}
                    message="温馨提示"
                    description="操作前，请先点击选择左侧需要选择的节点"
                    type="info"
                    showIcon
                />
        }
        return (


            <div className='formBoxStyle' style={{overflow:'hidden',height:'96%',backgroundColr:'#fff'}}>
                <div className='formTitle'>
                    <span className='left'>资源管理</span>
                    <Button type='primary' onClick={this.addNode} style={{margin:'2px 0px 0px 10px'}} >添加子节点</Button>
                    <Button  type='primary' onClick={this.addTopNode} style={{margin:'2px 0px 0px 10px'}}>新增主菜单</Button>
                    <Button  type='primary' onClick={this.deleteNode} style={{margin:'2px 0px 0px 10px'}}>刪除该节点</Button>
                </div>
                <Row  style={{height:containerHeight}}>
                    <Col  span={6} style={{backgroundColor:'#fff'}}>
                        <TreeComponent
                            ref = 'TreeComponent'
                            loading = {this.loading}
                            upDataForm = {this.upDataForm}
                            url="/base/resource/tree"
                            treeId = 'resourceId'
                            treeName = 'resourceName'
                            treeChildren = 'childResource'
                            titleClick = {true}
                            titleClickUrl = '/base/resource/r/'
                        />
                    </Col>
                    <Col span={18} style={{borderLeft:'1px solid #1d8ece',height:'100%',overflowY:'auto',overflowX:'hidden',padding:'30px 0px 30px 50px',backgroundColor:'#fff'}}>
                        {ele}
                    </Col>
                </Row>


            </div>
        );
    }
} 
export default Dimensions({
    getHeight: function(element) {
        return window.innerHeight - 165;
    },
    getWidth: function(element) {
        let widthOffset = 270;
        return window.innerWidth - widthOffset;
    },
    containerStyle: {marginLeft: 5, marginRight: 5 } //, transitionProperty: 'width', transitionDuration: '0.5s', transitionTimingFunction:'linear'
})(TreeAndForm);
